package com.trip.back.stage.system.controller;

import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.trip.back.stage.common.BaseController;
import com.trip.back.stage.common.result.JsonResult;
import com.trip.back.stage.common.result.PageResult;
import com.trip.back.stage.system.entity.SysRole;
import com.trip.back.stage.system.service.RoleService;

@RestController
@RequestMapping("/sys/role")
public class RoleController extends BaseController {

	@Autowired
	private RoleService roleService;
	
	@GetMapping("/all")
	public PageResult<SysRole> list(String keyword) {
		List<SysRole> list = roleService.getAll();
		if (keyword != null && !keyword.trim().isEmpty()) {
            keyword = keyword.trim();
	        Iterator<SysRole> iterator = list.iterator();
	        while (iterator.hasNext()) {
	            SysRole next = iterator.next();
	            boolean b = next.getId().contains(keyword) || next.getRoleName().contains(keyword) || next.getRoleDesc().contains(keyword);
	            if (!b) {
	                iterator.remove();
	            }
	        }
		}
        return new PageResult<>(list);
	}
	
	@GetMapping("/list")
	public PageResult<SysRole> list(Integer page, Integer limit, SysRole sysRole) {
		return roleService.getPageList(page, limit, sysRole);
	}
	
	@GetMapping("/{id}")
	public JsonResult query(@PathVariable String id) {
		return roleService.getRoleById(id);
	}
	
	@PostMapping("/add")
	public JsonResult add(@RequestBody SysRole sysRole) {
		sysRole.setCreateUser(super.getLoginUser().getAccount());
		sysRole.setUpdateUser(super.getLoginUser().getAccount());
		return roleService.addRole(sysRole);
	}
	
	@PostMapping("/edit")
	public JsonResult edit(@RequestBody SysRole sysRole) {
		sysRole.setUpdateUser(super.getLoginUser().getAccount());
		return roleService.editRole(sysRole);
	}
	
	@DeleteMapping()
	public JsonResult del(@PathVariable List<String> ids) {
		return roleService.delRoles(ids);
	}
	
}
